package org.ducinaltum.android.prima;

import java.util.Date;
import java.util.GregorianCalendar;

import org.ducinaltum.android.prima.services.DucInAltumService;
import org.ducinaltum.android.prima.services.DucInAltumService.State;
import org.ducinaltum.android.prima.services.ServiceException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

public class EventFormActivity extends Activity {

	private static final String START_DATE_STATE_KEY = "startDateState";

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_form);
        Spinner sState = (Spinner)findViewById(R.id.sState);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        		R.array.event_states, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sState.setAdapter(adapter);
        sState.setSelection(sState.getCount() - 1);
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.activity_event_form, menu);
        return true;
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
    	super.onSaveInstanceState(outState);
    	DatePicker dpStartDate = (DatePicker)findViewById(R.id.dpStartDate);
    	int[] startDate = {dpStartDate.getYear(), dpStartDate.getMonth(), dpStartDate.getDayOfMonth()};
    	outState.putIntArray(START_DATE_STATE_KEY, startDate);
    }

    @Override
    protected void onRestoreInstanceState(final Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	if (savedInstanceState.containsKey(START_DATE_STATE_KEY)) {
        	int[] startDate = savedInstanceState.getIntArray(START_DATE_STATE_KEY);
    		((DatePicker)findViewById(R.id.dpStartDate)).updateDate(startDate[0], startDate[1], startDate[2]);
    	}
    }

    public void searchEvents(final View view) {
    	DatePicker dpStartDate = (DatePicker)findViewById(R.id.dpStartDate);
		Date startDate = new GregorianCalendar(dpStartDate.getYear(), dpStartDate.getMonth(),
				dpStartDate.getDayOfMonth()).getTime();
		int stateIndex = ((Spinner)findViewById(R.id.sState)).getSelectedItemPosition();
		State state = stateIndex < State.values().length? State.values()[stateIndex]: null;

    	((Button)findViewById(R.id.bSearch)).setEnabled(false);
    	dpStartDate.setEnabled(false);
    	((ProgressBar)findViewById(R.id.pbSearch)).setVisibility(View.VISIBLE);

    	new SearchEventsTask().execute(startDate, state);
    }


    private class SearchEventsTask extends AsyncTask<Object, Void, long[]> {

    	protected long[] doInBackground(final Object... params) {
    		long[] ids = null;
			try { ids = new DucInAltumService().searchEvents((Date)params[0], (State)params[1]); }
			catch (ServiceException ex) {}
			return ids;
        }

        protected void onPostExecute(final long[] ids) {
			if (ids != null) {
				if (ids.length > 0) {
	   				Intent intent = new Intent(getApplicationContext(), EventPagerActivity.class);
	   				intent.putExtra(EventPagerActivity.INTENT_EXTRA_EVENT_IDS, ids);
	   				startActivity(intent);
				} else {
					String text = getResources().getString(R.string.msg_no_events_found);
					Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
				}
			} else {
				String errorText = getResources().getString(R.string.msg_events_error);
				Toast.makeText(getApplicationContext(), errorText, Toast.LENGTH_SHORT).show();
			}

			((ProgressBar)findViewById(R.id.pbSearch)).setVisibility(View.GONE);
			((DatePicker)findViewById(R.id.dpStartDate)).setEnabled(true);
			((Button)findViewById(R.id.bSearch)).setEnabled(true);
        }
    }
}
